import * as path from 'path';
import * as vscode from 'vscode';
import { GiteeApi, Gist } from './giteeApi';

export class GistProvider implements vscode.TreeDataProvider<vscode.TreeItem> {

  private _onDidChangeTreeData: vscode.EventEmitter<vscode.TreeItem | undefined> = new vscode.EventEmitter<vscode.TreeItem | undefined>();
  readonly onDidChangeTreeData: vscode.Event<vscode.TreeItem | undefined> = this._onDidChangeTreeData.event;
  private page = 1;
  private treeList: vscode.TreeItem[] = [];
  private moreLock = false;

  constructor(private api: GiteeApi) {
    this.getMoreGist().then(() => {
      this._onDidChangeTreeData.fire(undefined);
    });
  }

  public async getChildren(element?: vscode.TreeItem): Promise<vscode.TreeItem[]> {
    if (element) {
      return [];
      // return this.getAllBranch(element.project);
    }
    return this.treeList;
  }

  public async refresh() {
    this.page = 1;
    this.treeList = [];
    await this.getMoreGist();
    this._onDidChangeTreeData.fire(undefined);
  }

  public async more() {
    if (this.moreLock) {
      return;
    }
    this.moreLock = true;
    this.treeList.pop();
    await this.getMoreGist();
    this._onDidChangeTreeData.fire(undefined);
    this.moreLock = false;
  }

  public getTreeItem(element: vscode.TreeItem): vscode.TreeItem {
    return element;
  }

  public create(): void {
    this.refresh();
  }

  private async getMoreGist() {
    try {
      const list = await this.api.getGistList(this.page, this.limit);
      for (const item of list) {
        this.treeList.push(new GistItem(item, vscode.TreeItemCollapsibleState.Collapsed));
      }
      if (list.length > 0) {
        const more = new vscode.TreeItem('... 加载更多');
        more.command = {
          title: '加载更多',
          command: 'gitee.moreGist',
        };
        this.treeList.push(more);
      }
      this.page ++;
    } catch (error) {
      vscode.window.showErrorMessage(`获取代码片段列表失败: ${ error.toString() }`);
    }
  }

  private get limit() {
    return vscode.workspace.getConfiguration('gitee').get<number>('gistLimit') || 50;
  }
}

export class GistItem extends vscode.TreeItem {
  constructor(public gist: Gist, public readonly collapsibleState: vscode.TreeItemCollapsibleState) {
    super(gist.description, collapsibleState);
    this.description = `共${ Object.keys(gist.files).length }个文件`;
    this.iconPath = path.join(__dirname, `../media/${ gist.public ? 'gistPublic' : 'gistPrivate' }.svg`);
    this.contextValue = 'project';
  };
}